package api

import (
	"encoding/json"
	"github.com/julienschmidt/httprouter"
	"github.com/satori/go.uuid"
	"models"
	"net/http"
	"redis"
	"time"
	"utils"
)

const cookieName = "SESSIONID"

var EXPIRES, _ = time.ParseDuration("24h")

func updateCookie(sessionId string, w http.ResponseWriter) {
	var newTime = time.Now().Add(EXPIRES)
	http.SetCookie(w, &http.Cookie{
		Name:     cookieName,
		Value:    sessionId,
		HttpOnly: true,
		Expires:  newTime,
	})
}

func GetSession(w http.ResponseWriter, r *http.Request, _ httprouter.Params) (s models.Session) {
	sessionCookie, _ := r.Cookie(cookieName)
	var sessionId = ""
	if sessionCookie != nil {
		sessionId = sessionCookie.Value
	} else {
		uuid, _ := uuid.NewV4()
		sessionId = uuid.String()
	}
	updateCookie(sessionId, w)

	var info = redisServer.GetRedis(sessionId)

	if info == "" {
		info = utils.JSON(models.Session{sessionId, false, models.User{}})
	}
	redisServer.SaveRedis(sessionId, info)

	json.Unmarshal([]byte(info), &s)
	return
}
